package fi.foyt.cs.mail;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.google.appengine.api.utils.SystemProperty;

public class MailUtils {

  public static void sendMail(String subject, String content, String contentType, String fromEmail, String fromName, String toEmail, String toName) throws UnsupportedEncodingException, MessagingException {
    if (SystemProperty.environment.get().equals("Development")) {
      System.out.println(
        new StringBuilder()
          .append("-------- MAIL --------").append('\n')
          .append("to: " + toName + "<" + toEmail + ">").append('\n') 
          .append("from: " + fromName + "<" + fromEmail + ">").append('\n')
          .append("subject: " + subject).append('\n')
          .append("content: ").append('\n')
          .append('\n')
          .append(content)
          .append("-------- MAIL --------")
          .toString());
    } else {
      Properties props = new Properties();
      Session session = Session.getDefaultInstance(props, null);
      MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress(fromEmail, fromName, "UTF-8"));
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail, toName, "UTF-8"));
      message.setSubject(subject, "UTF-8");
      message.setContent(content, contentType + ";charset=\"utf-8\"");
      Transport.send(message);
    }
  }
}
